#define  _CRT_SECURE_NO_WARNINGS

#include "List.h"

LN* BuyList(LTDataType x)
{
	LN* newnode = (LN*)malloc(sizeof(LN));
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void ListPrint(LN* phead)
{
	LN* cur = phead->next;
	while (cur != phead)
	{
		printf("%d-> ", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

LN* ListInit()
{
	LN* phead = BuyList(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListDstroy(LN* phead)
{
	assert(phead);

	LN* cur = phead->next;
	while (cur != phead)
	{
		LN* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
	phead = NULL;
}

void ListPushBack(LN* phead, LTDataType x)
{
	assert(phead);

	/*LN* tail = phead->prev;
	LN* newnode = BuyList(x);

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/

	ListInsert(phead->prev, x);

}

void ListPushFront(LN* phead, LTDataType x)
{
	assert(phead);

	/*LN* first = phead->next;
	LN* newnode = BuyList(x);

	first->prev = newnode;
	newnode->prev = phead;
	newnode->next = first;
	phead->next = newnode;*/

	ListInsert(phead->next, x);
}

void ListPopBack(LN* phead)
{
	assert(phead);
	/*assert(phead->next != phead);

	LN* tail = phead->prev;
	LN* prevtail = tail->prev;
	prevtail->next = phead;
	phead->prev = prevtail;

	free(tail);
	tail = NULL;*/
	ListErase(phead->prev);
}

void ListPopFront(LN* phead)
{
	assert(phead);
	/*assert(phead->next!=phead);


	LN* first = phead->next;
	LN* second = first->next;
	second->prev = phead;
	phead->next = second;

	free(first);
	first = NULL;*/

	ListErase(phead->next);

}

LN* ListFind(LN* phead, LTDataType x)
{
	assert(phead);

	LN* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur=cur->next;
	}
	return NULL;
}

void ListInsert(LN* pos, LTDataType x)
{
	assert(pos);

	LN* prev = pos->prev;
	LN* newnode = BuyList(x);
	newnode->next = pos;
	pos->prev = newnode;
	newnode->prev = prev;
	prev->next = newnode;

}

void ListErase(LN* pos)
{
	assert(pos);

	LN* PosNext = pos->next;
	LN* PosPrev = pos->prev;
	PosNext->prev = PosPrev;
	PosPrev->next = PosNext;

	free(pos);
	pos = NULL;
}